<?php
namespace App\Services\WxMp;

use App\Models\WxMpList;
use App\Models\WxMpPayList;

/**
 * 微信支付业务逻辑类
 * @package App\Services\WxMp
 */
class WxMpPayListService
{
    /**
     * 获取有效的应用列表
     * @return array
     */
    public function getValidMpList($isRefresh = false)
    {
        $cacheKey = 'wx_mp_pay_list';
        $userData = \Cache::get($cacheKey);
        if (empty($userData) || $isRefresh) {
            try{
                $list = WxMpPayList::where('is_enable', 1)->get();
            }catch (\Exception $e){
                $list = [];
            }
            if ($list){
                \Cache::put($cacheKey, $userData, 60);
            }
        }
        return $list ? $list->toArray() : [];
    }
    /**
     * 保存应用
     * @param $request
     */
    public function save($request)
    {
        \DB::beginTransaction();
        try{
            if (empty($request->id)){
                $mpModel = new WxMpPayList();
                $findSame = WxMpPayList::where('appid', $request->appid)->first();
                if ($findSame){
                    throw new \Exception('已存在改AppID的微信应用');
                }
            }else{
                $mpModel = WxMpPayList::findOrFail($request->id);
            }
            $mpModel->nick_name = $request->nick_name ?? '';
            $mpModel->head_img = $request->head_img ?? '';
            $mpModel->appid = $request->appid ?? '';
            $mpModel->mch_id = $request->mch_id ?? '';
            $mpModel->key = $request->key ?? '';
            $mpModel->cert_path = $request->cert_path ?? '';
            $mpModel->key_path = $request->key_path ?? '';
            $mpModel->is_enable = $request->is_enable ?? 0;
            $mpModel->is_default = $request->is_default ?? 0;
            $mpModel->save();
            //清除其他默认
            if ($mpModel->is_default == 1){
                WxMpPayList::where('id', '<>', $mpModel->id)->update(['is_default'=>0]);
            }
            //更新后台微信应用列表
            $wxMpList = WxMpList::FirstOrNew([
                'appid' => $mpModel->appid,
                'is_from_open' => 1,
                'type' => WxMpListService::TYPE_PAYMENT,
            ]);
            $wxMpList->nick_name = $mpModel->nick_name;
            $wxMpList->head_img = $mpModel->head_img;
            $wxMpList->is_enable = $mpModel->is_enable;
            $wxMpList->save();
            //刷新缓存
            (new WxMpListService())->getValidMpList(true);
            //清除缓存
            $this->getValidMpList(true);
            \Db::commit();
        }catch (\Exception $e){
            \DB::rollBack();
            throw new \Exception($e->getMessage());
        }
        return true;
    }

    /**
     * 删除应用
     * @param $id
     * @return bool
     */
    public function del($id)
    {
        $find = WxMpPayList::findOrFail($id);
        $find->delete();
        $this->getValidMpList(true);
        return true;
    }
}